<template>
  <div class="rightPhone">
    <div class="phoneBox">
      <div class="tabs">
        <div
          v-for="item in menuList"
          :key="item.id"
          @click="handleClick(item)"
          class="tabList"
          :class="{ active: item.type == activeName }"
        >
          <span>{{ item.name }}</span>
          <el-icon :class="['el-icon-arrow-up', 'icon']">
            <ArrowDown />
          </el-icon>
        </div>
      </div>
      <!-- 手机号/邮箱 -->
      <div class="contact" v-if="activeName == 'contactInformation'">
        <div class="buttonChange">
          <el-tabs v-model="isType" class="demo-tabs" @tab-click="handleClickChange">
            <el-tab-pane
              v-for="items in contatList"
              :key="items.id"
              :label="items.name"
              :name="items.type"
            />
          </el-tabs>
        </div>
        <div class="menuScroll">
          <div class="listMenu" v-for="items in activeValue" :key="items.cid">
            <div class="flex justify-left items-center">
              <b class="titles" v-if="items.numberType == 1">{{ maskPhoneNumber(items.number) }}</b>
              <b class="titles" v-if="items.numberType == 0">{{ maskPhoneNumber(items.number) }}</b>
              <b class="titles" v-if="items.numberType == 3">{{ items.number }}</b>
              <el-tag v-if="items.primaryNum" type="danger" size="small" class="ml-10px"
                >疑似关键决策人</el-tag
              >
            </div>

            <div class="txt flex justify-left items-center flex-wrap" v-if="items.descList"
              >来源:
              <span class="ml-10px" v-for="(desc, index) in items.descList.split(',')" :key="index">
                <a :href="formatDesc(desc, 2)">{{ formatDesc(desc, 1) }}</a>
              </span></div
            >
            <p class="txt flex justify-left items-center" v-else
              >来源: <span class="ml-10px">企业公开信息</span></p
            >
            <div class="txt-mark" v-if="items.tag"
              >标记:
              <div class="entag">
                <EntTag
                  v-for="tag in items.tagList"
                  :key="tag.id"
                  :content="tag.content"
                  :bgColor="tag.bgColor"
                  :textColor="tag.textColor"
                />
              </div>
            </div>
            <p class="txt" v-if="items.remark"
              >备注: <span>{{ items.remark }}</span></p
            >
            <div v-if="received && authType != 2" class="receive">
              <el-button
                link
                type="primary"
                v-if="items.numberType == 1 || items.numberType == 0"
                @click="onCall(items)"
                >打电话</el-button
              >
              <el-button link type="primary" @click="openCustomerForm(items)">转客户</el-button>
              <el-button link type="primary" @click="openForm('edit', items, items.id)"
                >编辑</el-button
              >
            </div>
          </div>
          <div class="dialog" v-if="!received && activeValue.length != 0">
            <p class="dialogBtton" @click="receivEnterprise">领取企业</p>
            <p class="dialogType">{{ numberCount }}个联系方式</p>
          </div>
          <el-empty title="暂无数据" v-if="activeValue.length == 0" />
        </div>
      </div>
      <!-- 跟进记录 -->
      <div v-else class="contact">
        <el-timeline style="max-width: 260px" v-loading="isloading">
          <el-timeline-item v-for="activity in companyMap.list" :key="activity.id">
            <p>{{ activity.createTime }}</p>
            <p>{{ activity.content }}</p>
            <!-- 领取企业 -->
            <div v-if="activity.type == 'receive'">
              <span class="mar-box">
                <span class="mar-title">操作人:</span>
                <span>{{ receiveUser }}</span>
              </span>
              <span class="mar-box" style="color: #409eff">领取了企业</span>
            </div>
            <!-- 放回公海 -->
            <div v-if="activity.type == 'delete'">
              <span class="mar-box">
                <span class="mar-title">操作人:</span>
                <span>{{ receiveUser }}</span>
              </span>
              <span class="mar-box" style="color: #f56c6c"> 把企业放回公海</span>
            </div>
            <!-- tag -->
            <div v-if="activity.type == 'tag'">
              <span class="mar-box">
                <span class="mar-title">操作人:</span>
                <span>{{ receiveUser }}</span>
              </span>
              <span class="mar-box">
                <span class="mar-title">号码:</span>
                <span class="phoneNumber">{{ activity.number }}</span>
              </span>

              <div class="txt-marks">
                <span class="mar-title">标记:</span>
                <div class="entag">
                  <EntTag
                    v-for="tag in activity.tagList"
                    :key="tag.id"
                    style="margin-right: 0"
                    :content="tag.content"
                    :bgColor="tag.bgColor"
                    :textColor="tag.textColor"
                  />
                </div>
              </div>
            </div>
            <!-- 添加备注 -->
            <div v-if="activity.type == 'remark'">
              <span class="mar-box">
                <span class="mar-title">操作人:</span>
                <span>{{ receiveUser }}</span>
              </span>
              <span class="mar-box">
                <span class="mar-title">号码:</span>
                <span class="phoneNumber">{{ activity.number }}</span>
              </span>
              <span class="mar-box">
                <span class="mar-title">备注:</span>
                <span class="phoneRemark">{{ activity.remark }}</span>
              </span>
            </div>
            <!-- 电话 -->
            <div v-if="activity.type == 'call'">
              <span class="mar-box">
                <span class="mar-title">操作人:</span>
                <span>{{ receiveUser }}</span>
              </span>
              <span class="mar-box">
                <span class="mar-title">号码:</span>
                <span class="phoneNumber">{{ activity.number }}</span>
              </span>
              <span class="mar-box">
                <span class="mar-title">外呼:</span>
                <span v-if="!activity.callRecordUrl">暂无音频</span>
              </span>
              <AudioPlayers v-if="activity.callRecordUrl" :url="activity.callRecordUrl" />
            </div>
          </el-timeline-item>
        </el-timeline>
        <div class="pageBox" v-if="companyMap.total > 8">
          <Pagination
            small
            v-model:limit="companyMap.pageSize"
            v-model:page="companyMap.pageNo"
            :total="companyMap.total"
            layout="prev, pager, next"
            @pagination="paginaSet"
          />
        </div>
        <el-empty title="暂无数据" v-if="companyMap.list.length == 0" />
      </div>
    </div>
  </div>
  <CustomerForm ref="customerFormRef" @success="getList" />
  <ReceiveDataForm ref="formRef" @success="getList" />
</template>
<script setup lang="ts">
const props = defineProps({
  value: Object
})
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { followRecord, simpleList } from '@/api/ent/advanceSearch/index'
import CustomerForm from '../../../crm/customer/CustomerForm.vue'
import ReceiveDataForm from '../../receivedata/ReceiveDataForm.vue'
import { companyReceive, companyGetOne } from '@/api/ent/advanceSearch/index'
import { useSoftPhoneStore } from '@/store/modules/softPhone'
import { formatDate } from '@/utils/public'
import { usePhoneStore } from '@/store/modules/phone'
import { emitter } from '@/utils/eventBus.ts'

const useStore = usePhoneStore()
const useSoftPhone = useSoftPhoneStore()
const customerFormRef = ref(null)
const formRef = ref(null)
const activeName = ref('contactInformation')
const isType = ref('phone')
const activeValue = ref([])
// 是否领取企业
const received = ref(false)
// 领取企业的用户
const receiveUser = ref('')
// 企业的cid
const companyCid = ref('')
const isloading = ref(false)
// 企业的联系方式数量
const numberCount = ref(0)
const { wsCache } = useCache()
const authType = wsCache.get(CACHE_KEY.USER).tenantInfo.authType
const contatList = ref([
  {
    name: '手机',
    id: 3,
    type: 'phone',
    list: []
  },
  {
    name: '固话',
    id: 5,
    type: 'telPhone',
    list: []
  },
  {
    name: '邮箱',
    id: 4,
    type: 'email',
    list: []
  }
])
const menuList = ref([
  {
    id: 0,
    name: '联系方式',
    type: 'contactInformation',
    list: []
  },
  {
    id: 1,
    name: '跟进记录',
    type: 'followUpRecords',
    list: []
  }
])
const companyMap = reactive({
  pageNo: 1,
  pageSize: 8,
  total: 0,
  list: []
})
const emit = defineEmits(['refreshDetaill'])
watch(
  () => props.value,
  (val) => {
    let tel = []
    let email = []
    let telphone = []
    let primaryIndex = -1
    received.value = val.received
    receiveUser.value = val.receiveUser
    numberCount.value = val.numberCount
    isType.value = 'phone'
    if (val.numberList.length) {
      val.numberList.forEach((item, index) => {
        if (item.numberType == 1) {
          tel.push(item)
        } else if (item.numberType == 3) {
          email.push(item)
        } else if (item.numberType == 0) {
          telphone.push(item)
        }
      })
    }
    primaryIndex = tel.findIndex((item) => item.primaryNum)
    if (primaryIndex != -1) {
      const [item] = tel.splice(primaryIndex, 1)
      tel.unshift(item)
    }
    contatList.value[0].list = tel
    contatList.value[2].list = email
    contatList.value[1].list = telphone
    activeValue.value = tel
    if (val.companyInfo) {
      companyCid.value = val.companyInfo.cid
      getFollow(val.companyInfo.cid)
    }
  },
  { deep: true }
)
// 跟进记录列表
const getFollow = async (cid) => {
  let params = {
    entId: cid,
    pageNo: companyMap.pageNo,
    pageSize: companyMap.pageSize
  }
  const { list, total } = await followRecord({ ...params })
  list.map((item) => {
    item.createTime = formatDate(item.createTime)
  })
  companyMap.list = list
  companyMap.total = total
  isloading.value = false
}
// 跟进记录分页
const paginaSet = (val) => {
  const { page, limit } = val
  companyMap.pageNo = page
  companyMap.pageSize = limit
  isloading.value = true
  getFollow(companyCid.value)
}
// 联系/跟进切换
const handleClick = (item) => {
  activeName.value = item.type
}
// 电话号码转*
const maskPhoneNumber = (phone) => {
  if (received.value) return phone
  const start = phone.substring(0, 4)
  const end = phone.substring(9)
  const masked = '*****'
  return start + masked + end
}
// 手机/email 切换
const handleClickChange = (tab: TabsPaneContext, event: Event) => {
  activeValue.value = contatList.value[tab.index].list
}
// 打电话
const onCall = (row) => {
  emitter.emit('simCall', {
    callee: row.number,
    source: 'ent',
    sourceId: row.entId
  })
  emitter.emit('userCallCallee', row.number)
}
// 转客户
const openCustomerForm = (row) => {
  customerFormRef.value.openByEnt(row.entId, row.number)
}
//刷新numberList列表
const getList = async () => {
  getComponeyStatus()
}
// 编辑
const openForm = (type: string, data: any, id?: number) => {
  formRef.value.open(type, data, id)
}
// 领取企业
const receivEnterprise = async () => {
  isloading.value = true
  const result = await companyReceive({ ids: [companyCid.value] }).catch((res) => {
    isloading.value = false
  })
  if (result) {
    setTimeout(async () => {
      ElMessage.success('领取成功!')
      getComponeyStatus()
      isloading.value = false
    }, 3e2)
  } else {
    isloading.value = false
  }
}
// 获取最新的状态
const getComponeyStatus = async () => {
  const res = await companyGetOne({ cid: companyCid.value })
  receiveUser.value = res.receiveUser
  received.value = res.received
  emit('refreshDetaill', {
    received: res.received,
    receiveUser: res.receiveUser,
    numberList: res.numberList
  })
}

const formatDesc = (item, index) => {
  if (item.indexOf(';') != -1) {
    if (index == 2) {
      return item.split(';')[1]
    } else if (index == 1) {
      return item.split(';')[0]
    }
  } else {
    if (index == 2) {
      return 'javascript:void(0)'
    } else if (index == 1) {
      return item
    }
  }
}
</script>
<style lang="scss" scoped>
:deep(.el-timeline) {
  padding-left: 20px;
  .el-timeline-item {
    padding-top: 10px;
    padding-bottom: 10px;
    p {
      margin: 0;
      display: flex;
      flex-direction: column;
    }
  }
}
.mar-entag {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-content: flex-start;
  .ent-tag {
    margin-bottom: 5px;
  }
}
.mar-box {
  margin: 5px 0;
  display: flex;
  align-items: center;
  align-items: flex-start;

  .mar-title {
    width: 44px;
    text-align: left;
    font-size: 13px;
    color: #999;
    margin-right: 6px;
  }
  span {
    font-size: 13px;
    color: #333;
  }
}

:deep(.el-tabs__item) {
  width: 33%;
}
:deep(.el-tabs__nav) {
  width: 100%;
}
.phoneNumber {
  color: #5b83fd;
}
.phoneRemark {
  color: #ab73ff;
}

.txt-marks {
  width: 100%;
  display: flex;
  font-size: 13px;
  color: #999;
  .mar-title {
    width: 44px;
  }
  .entag {
    width: calc(100% - 44px);
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: flex-start;
    .ent-tag {
      margin-bottom: 10px;
    }
  }
}
.rightPhone {
  width: 300px;
  margin-left: 10px;
  background-color: #f5f7f9;
  // padding-top: 10px;
  .phoneBox {
    width: 100%;
    height: 100%;
    background-color: #fff;
    border-radius: 4px 0 0 0;
    .menuScroll {
      height: calc(100% - 64px);
      overflow: auto;
      position: relative;
      .dialog {
        position: fixed;
        width: 298px;
        height: calc(100vh - 165px);
        bottom: 0;
        right: 0;
        backdrop-filter: blur(5px);
        -webkit-backdrop-filter: blur(5px);
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .dialogBtton {
          padding: 7.5px 12px;
          color: #fff;
          font-size: 12px;
          opacity: 0.9;
          background-color: #0052cc;
          border: none;
          border-radius: 4px;
          cursor: pointer;
          margin-bottom: 12px;
        }
        .dialogType {
          margin-top: 12px;
          font-size: 16px;
          opacity: 0.9;
          color: #666;
        }
      }
      .receive {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-top: 10px;
        .el-button {
          margin-left: 0;
          margin-right: 12px;
        }
      }
      .listMenu {
        padding: 10px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: flex-start;
        border-bottom: 1px solid #d6d6d8;
        // box-shadow: -5px 2px 5px rgba(0, 0, 0, 0.2);
        .titles {
          color: #333;
          margin: 2px 0;
          font-weight: bolder;
        }
        .txt-mark {
          width: 100%;
          display: flex;
          font-size: 13px;
          color: #999;
          .entag {
            width: calc(100% - 32px);
            display: flex;
            flex-wrap: wrap;
            justify-content: flex-start;
            align-items: flex-start;
            .ent-tag {
              margin-bottom: 10px;
            }
          }
        }
        .txt {
          margin: 8px 0;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          font-size: 13px;
          color: #999;
          text-overflow: ellipsis;
          overflow: hidden;
          word-break: break-all;
          white-space: nowrap;
          span {
            color: #333;
          }
        }
      }
      &::-webkit-scrollbar {
        width: 2px;
      }
      &::-webkit-scrollbar-track {
        background: #f1f1f1;
      }
      &::-webkit-scrollbar-thumb {
        background: #d8d8d8;
      }
      &::-webkit-scrollbar-thumb:hover {
        background: #d8d8d8;
      }
      &::-webkit-scrollbar-thumb:horizontal:start {
        border-top-left-radius: 4px;
        border-bottom-left-radius: 4px;
      }
      &::-webkit-scrollbar-thumb:horizontal:end {
        border-top-right-radius: 4px;
        border-bottom-right-radius: 4px;
      }
    }

    .tabs {
      width: 100%;
      display: flex;
      color: #333;
      font-size: 14px;
      padding-bottom: 4px;
      border-bottom: 1px solid #f5f7f9;
      .tabList {
        width: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 10px;
        cursor: pointer;
        position: relative;
        &.active {
          color: #5b83fd;
          &::after {
            content: '';
            position: absolute;
            left: 45%;
            transform: translateX(-50%);
            bottom: 0;
            width: 20px;
            height: 2px;
            background: #5b83fd;
          }
        }
        &:hover {
          color: #5b83fd;
        }
      }

      .content {
        width: 100%;
        overflow: auto;
      }
    }
    .contact {
      height: calc(100% - 50px);
      overflow-y: auto;
      .buttonChange {
        padding: 0 20px;
      }
      .pageBox {
        width: 100%;
        display: flex;
        justify-content: center;
      }
      &::-webkit-scrollbar {
        width: 2px;
      }
      &::-webkit-scrollbar-track {
        background: #f1f1f1;
      }
      &::-webkit-scrollbar-thumb {
        background: #d8d8d8;
      }
      &::-webkit-scrollbar-thumb:hover {
        background: #d8d8d8;
      }
      &::-webkit-scrollbar-thumb:horizontal:start {
        border-top-left-radius: 4px;
        border-bottom-left-radius: 4px;
      }
      &::-webkit-scrollbar-thumb:horizontal:end {
        border-top-right-radius: 4px;
        border-bottom-right-radius: 4px;
      }
    }
  }
}
</style>
